package falcon.protocol;

import falcon.common.Errno;
import falcon.common.Log;

public abstract class Packet {
	// version cmd bytes
	public int header = 0;
	public int id;
	
	public static final int getVersion(int header) {
		return (header >> 28) & 0x7;
	}
	
	public int getVersion() {
		return Packet.getVersion(this.header);
	}
	
	public void setVersion(int version) {
		this.header |= (version & 0x7) << 28;
	}
	
	public static final int getCmd(int header) {
		return (header >> 16) & 0xff;
	}
	
	public int getCmd() {
		return Packet.getCmd(this.header);
	}
	
	public void setCmd(int cmd) {
		this.header |= (cmd & 0xff) << 16;
	}
	
	public int getBytes() {
		return this.header & 0xffff;
	}
	
	public void setBytes(int bytes) {
		this.header |= (bytes & 0xffff);
	}
	
	public int setFieldValue(String name, Object value) {
		int errno = Errno.SUCCESS;
		try {
			getClass().getField(name).set(this, value);
		} catch (Exception e) {
			errno = Errno.COM_CATCH_EXCEPTION;
			Log.log(e, "set field value error;name=%s;value=%s", name, value);
		}
		return errno;
	}
	
	public Object getFieldValue(String name) {
		Object value = null;
		try {
			value = getClass().getField(name).get(this);
		} catch (Exception e) {
			value = null;
			Log.log(e, "get field value error;name=%s", name);
		}
		return value;
	}
}
